<template>
  <div class="swStMarketingTicket">
    <basic-container>
      <avue-crud
        ref="crud"
        :option="option"
        :table-loading="listLoading"
        :data="list"
        :page.sync="page"
        @search-change="handleFilter"
        @selection-change="selectionChange"
        @refresh-change="refreshChange"
        @on-load="getList">
        <template slot="searchMenu" slot-scope="{row,size}">
          <el-button :size="size" @click="()=>{setSearchFiledsEmpty(row);setSearchFiledsEmpty(searchForm);getList()}" icon="el-icon-delete">清空</el-button>
        </template>
        <template slot-scope="scope" slot="conductorIdSearch">
          <el-select v-model="searchForm.conductorId" placeholder="请选择" style="width: 150px" @change="changeLine" filterable>
            <el-option
              v-for="(item,index) in userList"
              :key="index"
              :label="item.username"
              :value="item.userCode">
            </el-option>
          </el-select>
        </template>
        <template slot="search" slot-scope="{row,size}">
          <el-form-item label="日期">
            <el-date-picker
              :size="size"
              v-model="searchForm.opertorTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="日期">
            </el-date-picker>
          </el-form-item>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button type="text" size="small" plain @click.stop="previewEditor(scope.row)">预览</el-button>
        </template>
        <template slot-scope="scope" slot="menuRight">
          <el-button
            type="primary"
            size="small"
            @click="createReconciliationData"
          >生成转账团购对账数据</el-button>
          <el-button type="primary"  size="mini" @click="batchAudit">一键审核</el-button>
          <el-button type="primary" size="mini" @click="submitData">加入报表差错</el-button>
          <el-button type="primary"  size="mini" @click="exportData">导出</el-button>
        </template>
      </avue-crud>
      <open-dialog
        :DialogVisible.sync="editVisableDialog"
        title="生成库存对比"
        width="40%"
      >
        <el-form label-width="60px" v-if="editVisableDialog">
          <avue-form
            v-model="formCreate"
            :option="createFareOption"
            style="margin-bottom: 40px"
          ></avue-form>
          <div class="bottom-menu-market">
            <el-button type="primary" :loading="loading" @click="editFare()">生成</el-button>
            <el-button type="primary" @click="editVisableDialog = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
    </basic-container>
<preview v-if="isPreview" ref="preview"></preview>
    <addReportEditor ref="addReportEditor" @addReportSuccess="getList"></addReportEditor>
  </div>
</template>

<script>
  import {getForm, postForm} from '@/api/gen/gen'
  import {mapGetters} from 'vuex';
  import ElInput from "../../../../../node_modules/element-ui/packages/input/src/input";
  import {setSearchFiledsEmpty} from "../../../../api/subwayRat/commonCheck";
  import {exportDataToExcel} from "../../../../api/subwayRat/exportSelf";
  import transitUtil from "../../../../api/subwayRat/transitUtil";
  import preview from './preview';
  import {
    tableOption, getSwStMarketingTicket, getSysUserToLine, batchAduitSwStMarketingTicket, createFares
  } from '../../../../api/subwayRat/conductorDifferences/swAuConductorShort/swStMarketingTicket';
  import {getSwStInputPassengerWork} from "../../../../api/subwayRat/conductorDifferences/passengersTransaction/passengersTransactionAudit/swStInputPassengerWork";
  import addReportEditor from '@/views/subwayRat/reportMondify/reportMistakeInfo/Editor';

  export default {
    components: {ElInput,preview,addReportEditor},
    name: 'swStMarketingTicket',
    data() {
      return {
        userList:[],
        selectKeys:[], //存放对像
        selectKeyVals:[], //存放值
        rowData:{},
        option: tableOption,
        loading: false,
        listLoading: true,
        isPreview: false,
        searchForm:{},
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          current: 1,// 当前页数
          pageSize: 20, // 每页显示多少条,
          size: 20,// 每页显示多少条
          isAsc: false// 是否倒序
        },
        list : [],
        formCreate: {},
        editVisableDialog: false,
      }
    },
    computed: {
      createFareOption(){
      return {
        emptyBtn: false,
        submitBtn: false,
        column: [ {
          "type": "date",
          "label": "交易开始日期",
          "prop": "startDate",
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          rules: [
            {
              required: true,
              message: '请选择交易开始日期',
              trigger: 'blur'
            }
          ]
        }, {
          "type": "date",
          "label": "交易结束日期",
          "prop": "endDate",
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          rules: [
            {
              required: true,
              message: '请选择交易结束日期',
              trigger: 'blur'
            }
          ]
        }]
      }
    }
    },
    watch: {
    },
    mounted() {
      getSysUserToLine({}).then((response)=>{
        this.userList = response.data.data;
      });

     //this.otherVueAction();

    // this.otherVueActionA();
    },
    created() {
    },
    methods: {
      setSearchFiledsEmpty,
      refreshChange() {
        this.getList()
      },
      changeLine(row){
      },
      previewEditor(row){
        this.isPreview = true;
        this.rowData = row;
      },
      async exportData(){ // 导出
        this.searchForm.pageNo=1;
        this.searchForm.pageSize=1000000000;
        this.searchForm.size=1000000000;
        if(this.selectKeys.length>0){
          let newData = JSON.parse(JSON.stringify(this.selectKeys));
          exportDataToExcel(newData,this.option.column,'营销车票数据审核');
        }else {
          let res=await getSwStMarketingTicket(this.searchForm);
          let data = res.data.data.records;
          exportDataToExcel(data,this.option.column,'营销车票数据审核');
        }
      },
      getList() {
        const params = this.$route.query;
        const p = {};
        if (Object.keys(params).length) {
          p.lineCode = params.lineCode;
          p.stationCode = params.stationCode;
          p.opertorTime = params.recordTime;
          p.conductorJobNo = params.conductorJobNo;
	        p.sourceQueryFlag = '1';//判断是售票员票款差异审核跳转过来的
        }
        this.listLoading = true;
        this.page.size = this.page.pageSize;
        this.page.current = this.page.currentPage;
        Object.assign(this.searchForm, this.page);
        this.searchForm.userCode = this.$store.getters.userInfo.userCode;
        this.searchForm.isTotalZero = 1;
        getSwStMarketingTicket(Object.keys(params).length ? p : this.searchForm).then(response => {
          this.list = response.data.data.records;
          this.listLoading = false;
          this.page.total = response.data.data.total;
        });
      },
      async batchAudit(row){
        if(this.selectKeys.length<=0){
          this.$message.warning("请选择数据");
          return;
        }
        let res = await this.$confirm('审核前请检查收入对账电子回执单对账状态？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        });
        if (!res) {
          return;
        }
        for(let i=0;i<this.selectKeys.length;i++){
          if(this.selectKeys[i].auditStatus==1){
            this.$message.success("已经审核通过的数据不可再审核！");
            return;
          }
        }
        let _this=this;
        this.$confirm('是否审批通过', '提示', {
          confirmButtonText: '通过',
          cancelButtonText: '不通过',
          type: 'warning'
        }).then(function () {
          batchAduitSwStMarketingTicket({ids:_this.selectKeyVals.join(','),auditStatus:1}).then(res=>{
            if(res.data.code==0){
              _this.$message.success("操作成功！");
            }else{
              _this.$message.success("操作失败！");
            }
            _this.getList();
          })
        }).catch(data => {
          batchAduitSwStMarketingTicket({ids:_this.selectKeyVals.join(','),auditStatus:2}).then(res=>{
            if(res.data.code==0){
              _this.$message.success("操作成功！");
            }else{
              _this.$message.success("操作失败！");
            }
            _this.getList();
          })
        })

      },
      async submitData() {
        if (this.selectKeys.length != 1) {
          this.$message.warning("请选择一条要加入的数据！");
          return;
        }

        let res = await this.$confirm('是否提交报表差错？', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        });
        if (!res) {
          return;
        }
        this.selectKeys[0].reportNameId = '1';
        let param={
          resultIds:this.selectKeys[0].id,
          operatorTable:"sw_st_marketing_ticket",
          lineCode:this.selectKeys[0].lineCode,
          stationCode:this.selectKeys[0].stationCode,
          reprotTime:this.selectKeys[0].opertorTime,
          reportNameId:8,
          userCodes:this.selectKeys[0].conductorJobNo,
          showType:3,
          dataSource:10,
          deviceNo:this.selectKeys[0].deviceOperateNum,
          bomCode:this.selectKeys[0].bomCode,
        };
        this.$refs.addReportEditor.others_report_add_call(param);

      },
      handleFilter(params, done) {
        Object.assign(this.searchForm,params);
        this.getList()
        done()
      },
      selectionChange(list){
        this.selectKeys=list;
        this.selectKeyVals=[];
        for(let i=0;i<list.length;i++){
          this.selectKeyVals.push(list[i].id);
        }
      },
      otherVueAction(){ //供其他Vue页面调用
        let th=this;
        transitUtil.$on('swStMarketingTicket_call',(param)=>{
          let p={};
          p.lineCode=param.lineCode;
          p.stationCode=param.stationCode;
          p.opertorTime=param.recordTime;
          p.conductorJobNo=param.conductorJobNo;
	        p.sourceQueryFlag='1';//判断是售票员票款差异审核跳转过来的
          getSwStMarketingTicket(p).then((response)=>{
            this.list = response.data.data;
            this.listLoading = false;
            this.page.total=response.data.total;
          });
        });
      },
      async createReconciliationData(){
        let res = await this.$confirm('操作后原来已确认的数据需要再次重新确认？', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        });
        if (!res) {
          return;
        }
        this.editVisableDialog = true;
      },
      editFare(){
        this.loading = true;
        createFares(this.formCreate)
        .then(data => {
          this.$message.success('生成成功！')
          this.editVisableDialog = false
          this.refreshChange()
          this.loading = false;
        }).catch(error=> {
          if(error.message.indexOf('timeout')!=-1){
            this.$message.warning('生成需要一定时间，请稍后查看!')
            this.editVisableDialog=false
            this.refreshChange()
            this.loading = false;
          }else{
            this.loading = false;
          }
        });
      }
    }
  }
</script>
<style lang="scss">
.bottom-menu-market {
  margin-top: -30px;
  text-align: center;
}
</style>
